package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/userInfo")
public class UserInfoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 从请求中的会话拿到客户端 用户的信息
        HttpSession session = req.getSession(false);
        // 判断session 和 user对象是否存在
        resp.setContentType("text/html; charset=utf8");
        if (session == null) {
            resp.getWriter().write("您当前处于未登录状态");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // user 对象不存在,用户当前处于未登录状态
            resp.getWriter().write("您当前处于未登录状态");
            return;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        user.setPassword("");
        resp.setContentType("application/json; charset=utf8");
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
